//
//  ListView.swift
//  SampleSwiftUI
//
//  Created on 10/7/23.
//

import SwiftUI
import UniformTypeIdentifiers

struct ListClipboardView: View {
    
    private struct ListItem: Identifiable, Transferable {
        let id = UUID()
        
        var value: String
        
        init(_ value: String) {
            self.value = value
        }
        
        static var transferRepresentation: some TransferRepresentation {
            ProxyRepresentation(exporting: \.value, importing: { value in ListItem(value) })
        }
    }
    
    @State private var items  = [
        ListItem("0"),
        ListItem("1"),
        ListItem("2")
    ]
    
    @State private var multiSelection = Set<UUID>()
    
    var body: some View {
        List(items, selection: $multiSelection) { item in
            Text(item.value)
        }
//        .copyable(items.filter { multiSelection.contains($0.id) })
//        .cuttable(for: ListItem.self) { items.filter { multiSelection.contains($0.id) } }
//        .pasteDestination(for: ListItem.self) { pastedItems in
//            items.append(contentsOf: pastedItems)
//        }
        .onCopyCommand {
            return items
                .filter({ multiSelection.contains($0.id) })
                .map { item in
                    NSItemProvider(item: item.value as NSString, typeIdentifier: UTType.SampleText.identifier)
                }
        }
        .onPasteCommand(of: [UTType.SampleText.identifier]) { providers in
            for provider in providers {
                provider.loadItem(forTypeIdentifier: UTType.SampleText.identifier) { (item, error) in
                    if let data = item as? Data {
                        do {
                            let dataDecoded = try NSKeyedUnarchiver.unarchivedObject(ofClass: NSString.self, from: data)
                            let value = dataDecoded! as String
                            print("Pasted item: \(value)")
                            items.append(ListItem(value))
                        } catch let err as NSError {
                            print("\(err.localizedDescription)")
                        }
                    }
                }
            }
        }
    }
}

struct ListView_Previews: PreviewProvider {
    static var previews: some View {
        ListClipboardView()
    }
}

extension UTType {
    static var SampleText: UTType {
        UTType(exportedAs: "com.sample.clipboard.text")
    }
}
